<template>
  <view id="sample">
    <uni-list>
      <view class="sub-title">
        <view>取样过程</view>
        <button
          type="primary"
          class="title-btn"
          @click="getNetworkData"
          v-if="networkData"
        >
          同步离线数据
        </button>
      </view>
      <uni-list-item clickable showArrow @click="takeAuth" :border="false">
        <template v-slot:header>
          <view
            class="zljcIcon zljc-icon-shenfenrenzheng"
            style="font-size: 64px; color: #1677ff"
            v-if="!portraitImageSrc"
          ></view>
          <view
            @click.stop="testPieceDemo(1)"
            v-else
            style="width: 64px; display: flex; justify-content: center"
          >
            <image
              :src="portraitImageSrc"
              mode="heightFix"
              style="height: 64px"
            ></image>
          </view>
        </template>
        <template v-slot:body>
          <view class="slot-body">
            <text class="slot-title">取样人员照片</text>
            <view class="slot-font"
              ><text
                >取样人员免冠半身照，面部特征拍摄清楚，能看到取样现场背景。</text
              ></view
            >
          </view>
        </template>
      </uni-list-item>
      <uni-list-item clickable showArrow @click="takePicture" :border="false">
        <template v-slot:header>
          <view
            class="zljcIcon zljc-icon-erweima"
            style="font-size: 64px; color: #1677ff"
            v-if="!ewmImageSrc"
          ></view>
          <view
            @click.stop="testPieceDemo(2)"
            v-else
            style="width: 64px; display: flex; justify-content: center"
          >
            <image
              :src="ewmImageSrc"
              mode="heightFix"
              style="height: 64px"
            ></image>
          </view>
        </template>
        <template v-slot:body>
          <view class="slot-body">
            <text class="slot-title">二维码标识照片</text>
            <view class="slot-font"
              ><text
                >手持一组待植入的固定唯一标识二维码，唯一标识二维码清晰可见，背景图片为待取样植入唯一标识的一组试件。</text
              ></view
            >
            <view class="slot-link" @click.stop="testPieceDemo(3)"
              ><text>查看样例</text></view
            >
          </view>
        </template>
      </uni-list-item>
      <view class="help">
        <view class="help-text"
          ><uni-icons type="" color="#333" size="18" />封样过程</view
        >
        <picker
          @change="mePickerChange"
          :value="meIndex"
          :range="meOptions"
          range-key="name"
        >
          <view class="uni-input">{{ meOptions[meIndex].name }}</view>
          <uni-icons
            class="arrowright"
            type="arrowright"
            color="#bbb"
            size="16"
          />
        </picker>
      </view>
      <!-- 随机试件 -->
      <template v-if="specimenNums > 0">
        <uni-list-item
          v-for="(item, index) in specimenNumsRrr"
          clickable
          showArrow
          @click="takeTestPiece(item)"
          :border="false"
        >
          <template v-slot:header>
            <view
              class="zljcIcon zljc-icon-jingquezhunque"
              style="font-size: 64px; color: #1677ff"
              v-if="imagesrcLater[item - 1] == item"
            ></view>
            <view @click.stop="openPopup4(item)" class="test-piece" v-else>
              <image
                :src="
                  typeof imagesrcLater[index] != 'number'
                    ? imagesrcLater[index].url
                    : ''
                "
                mode="heightFix"
                style="height: 64px"
              ></image>
            </view>
          </template>
          <template v-slot:body>
            <view class="slot-body">
              <text class="slot-title">试件{{ item }}照片</text>
              <!--  -->
              <view v-if="randomPostion == 'true'" class="slot-font"
                ><text
                  >已植入二维码唯一标识，编号数字尾号为{{
                    item
                  }}的试件。要求唯一标识二维码值不得有遮挡及污损，唯一标识二维码值、防调换副标签及摸具清晰可见，且不能将其他试件二维码唯一标识防调换副标签摄入图中。</text
                ></view
              >
              <view v-else class="slot-font"
                ><text
                  >要求唯一标识二维码值不得有遮挡及污损，唯一标识二维码及摸具清晰可见，且不能将其他试件二维码标识签植入图片中。</text
                ></view
              >
              <view class="slot-link" @click.stop="testPieceDemo(4)"
                ><text>查看样例</text></view
              >
            </view>
          </template>
        </uni-list-item>
      </template>
      <!-- 试件1照片 -->
      <uni-list-item
        v-if="
          randomPostion == 'true' &&
          (specimenNums <= 0 || specimenNums == 'null')
        "
        clickable
        showArrow
        @click="takeTestPiece(1)"
        :border="false"
      >
        <template v-slot:header>
          <view
            class="zljcIcon zljc-icon-jingquezhunque"
            style="font-size: 64px; color: #1677ff"
            v-if="imagesrcLater[0] == 1"
          ></view>
          <view @click.stop="openPopup4(1)" class="test-piece" v-else>
            <image
              :src="
                typeof imagesrcLater[0] != 'number' ? imagesrcLater[0].url : ''
              "
              mode="heightFix"
              style="height: 64px"
            ></image>
          </view>
        </template>
        <template v-slot:body>
          <view class="slot-body">
            <text v-if="randomPostion == 'true'" class="slot-title"
              >试件1照片</text
            >
            <view v-if="randomPostion == 'true'" class="slot-font"
              ><text
                >已植入二维码唯一标识，编号数字尾号为1的试件。要求唯一标识二维码值不得有遮挡及污损，唯一标识二维码值、防调换副标签及摸具清晰可见，且不能将其他试件二维码唯一标识防调换副标签摄入图中。</text
              ></view
            >
            <view class="slot-link" @click.stop="testPieceDemo(4)"
              ><text>查看样例</text></view
            >
          </view>
        </template>
      </uni-list-item>
      <!-- 试件2照片 -->
      <uni-list-item
        v-if="
          randomPostion == 'true' &&
          (specimenNums <= 0 || specimenNums == 'null')
        "
        clickable
        showArrow
        @click="takeTestPiece(2)"
        :border="false"
      >
        <template v-slot:header>
          <view
            class="zljcIcon zljc-icon-jingquezhunque"
            style="font-size: 64px; color: #1677ff"
            v-if="imagesrcLater[1] == 2"
          ></view>
          <view @click.stop="openPopup4(2)" class="test-piece" v-else>
            <image
              :src="
                typeof imagesrcLater[1] != 'number' ? imagesrcLater[1].url : ''
              "
              mode="heightFix"
              style="height: 64px"
            ></image>
          </view>
        </template>
        <template v-slot:body>
          <view class="slot-body">
            <text v-if="randomPostion == 'true'" class="slot-title"
              >试件2照片</text
            >
            <view v-if="randomPostion == 'true'" class="slot-font"
              ><text
                >已植入二维码唯一标识，编号数字尾号为2的试件。要求唯一标识二维码值不得有遮挡及污损，唯一标识二维码值、防调换副标签及摸具清晰可见，且不能将其他试件二维码唯一标识防调换副标签摄入图中。</text
              ></view
            >
            <view class="slot-link" @click.stop="testPieceDemo(4)"
              ><text>查看样例</text></view
            >
          </view>
        </template>
      </uni-list-item>
      <!-- 试件3照片 -->
      <!-- {{specimenNums }} -->
      <uni-list-item
        v-if="
          randomPostion == 'true' &&
          (specimenNums <= 0 || specimenNums == 'null')
        "
        clickable
        showArrow
        @click="takeTestPiece(3)"
        :border="false"
      >
        <template v-slot:header>
          <view
            class="zljcIcon zljc-icon-jingquezhunque"
            style="font-size: 64px; color: #1677ff"
            v-if="imagesrcLater[2] == 3"
          ></view>
          <view @click.stop="openPopup4(3)" class="test-piece" v-else>
            <image
              :src="
                typeof imagesrcLater[2] == 'number' ? '' : imagesrcLater[2].url
              "
              mode="heightFix"
              style="height: 64px"
            ></image>
          </view>
        </template>
        <template v-slot:body>
          <view class="slot-body">
            <text v-if="randomPostion == 'true'" class="slot-title"
              >试件3照片</text
            >
            <view v-if="randomPostion == 'true'" class="slot-font"
              ><text
                >已植入二维码唯一标识，编号数字尾号为3的试件。要求唯一标识二维码值不得有遮挡及污损，唯一标识二维码值、防调换副标签及摸具清晰可见，且不能将其他试件二维码唯一标识防调换副标签摄入图中。</text
              ></view
            >
            <view class="slot-link" @click.stop="testPieceDemo(4)"
              ><text>查看样例</text></view
            >
          </view>
        </template>
      </uni-list-item>
      <!-- 试件照片 -->
      <uni-list-item
        v-if="
          randomPostion != 'true' &&
          (specimenNums <= 0 || specimenNums == 'null')
        "
        clickable
        showArrow
        @click="takeTestPiece"
        :border="false"
      >
        <template v-slot:header>
          <view
            class="zljcIcon zljc-icon-jingquezhunque"
            style="font-size: 64px; color: #1677ff"
            v-if="imagesrc.length == 0"
          ></view>
          <view
            @click.stop="$refs.popup4.open('center')"
            class="test-piece"
            v-else
          >
            <image
              :src="imagesrc[imagesrc.length - 1].url"
              mode="heightFix"
              style="height: 64px"
            ></image>
          </view>
        </template>
        <template v-slot:body>
          <view class="slot-body">
            <text class="slot-title">试件封样照片</text>
            <view class="slot-font"
              ><text
                >要求唯一标识二维码值不得有遮挡及污损，唯一标识二维码及摸具清晰可见，且不能将其他试件二维码标识签植入图片中。</text
              ></view
            >
            <view class="slot-link" @click.stop="testPieceDemo(4)"
              ><text>查看样例</text></view
            >
          </view>
        </template>
      </uni-list-item>
      <uni-list-item clickable showArrow @click="takeVideo" :border="false">
        <template v-slot:header>
          <view
            class="zljcIcon zljc-icon-yingxiangguanli"
            style="font-size: 50px; color: #1677ff"
            v-if="!testVideoUrl"
          ></view>
          <view style="width: 64px; height: 64px" v-else>
            <video
              :src="testVideoUrl"
              id="video"
              style="width: 64px; height: 64px"
              @play="handlePlay"
            ></video>
          </view>
        </template>
        <template v-slot:body>
          <view class="slot-body">
            <text class="slot-title">试件音视频</text>
            <view class="slot-font"
              ><text
                >视频中，试件清晰可见且能看到取样背景“录制时必须说xxx（姓名）xxx年xx月xx日上午/下午，在xxx工程完成xx检测类别，封样完成”。</text
              ></view
            >
            <view class="slot-link" @click.stop="videoShow"
              ><text>查看样例</text></view
            >
          </view>
        </template>
      </uni-list-item>
      <!-- <uni-list-item v-if="projectInfo.bim || projectInfo.panoramic">
				<template v-slot:header>
					<view class="zljcIcon zljc-icon-bim_tianjiahe" style="font-size:64px;color:#1677FF;"></view>
				</template>
				<template v-slot:body>
					<view class="slot-body">
						<text class="slot-title">实景定位</text>
						<view class="slot-font"><text>视在BIM/全景中选取取样位置并标记定位，记录取样位置信息。</text></view>
						<view class="slot-link">
							<text class="u-margin-right-20" @click="bim()" v-if="projectInfo.bim">BIM取样位置定位</text> 
							<text @click="overallView()" v-if="projectInfo.panoramic">全景取样位置定位</text>
						</view>
					</view>
				</template>
			</uni-list-item> -->
    </uni-list>

    <view class="bottom-nav"
      ><button type="primary" class="btn" @click="save">下一步</button></view
    >

    <!-- 创建照片画布-用于自定义水印、方框等 -->
    <canvas
      id="canvas-clipper"
      canvas-id="canvas-clipper"
      type="2d"
      :style="{
        width: canvasSiz.width + 'px',
        height: canvasSiz.height + 'px',
        position: 'fixed',
        top: 0,
        left: '-' + canvasSiz.width + 'px',
      }"
    />

    <!-- 点击按钮全屏播放视频 -->
    <view v-if="videoPlay">
      <video
        controls
        id="testvideo"
        autoplay="true"
        :src="videoUrl"
        @fullscreenchange="screenChange"
      ></video>
    </view>

    <!-- 试件照片已上传列表 -->
    <uni-popup ref="popup4" background-color="#fff">
      <scroll-view scroll-y="true" style="width: 260px; max-height: 500px">
        <view
          class="preview-img"
          v-for="(image, index) in imagesrcLater"
          :key="index"
          style="width: 240px"
        >
          <template
            v-if="
              index + 1 == indexIMg &&
              (randomPostion == 'true' || specimenNums > 0)
            "
          >
            <image
              :src="image.url"
              style="width: 240px"
              mode="widthFix"
            ></image>
            <uni-icons
              type="clear"
              size="20"
              color="#F56C6C"
              class="img-icon"
              @tap="delectImg(index)"
            ></uni-icons>
          </template>
          <template
            v-else-if="
              randomPostion != 'true' &&
              (specimenNums <= 0 || specimenNums == 'null')
            "
          >
            <image
              :src="image.url"
              style="width: 240px"
              mode="widthFix"
            ></image>
            <uni-icons
              type="clear"
              size="20"
              color="#F56C6C"
              class="img-icon"
              @tap="delectImg(index)"
            ></uni-icons>
          </template>
        </view>
      </scroll-view>
    </uni-popup>
    <!-- 失败后 -->
    <uni-popup ref="popup6" class="tips-popup" background-color="#fff">
      <scroll-view scroll-y="true" style="width: 260px; max-height: 500px">
        <view
          class="preview-img"
          v-for="(image, index) in loseGeneratedBoxList"
          :key="index"
          style="width: 240px"
        >
          <image :src="image" style="width: 240px" mode="widthFix"></image>
          <uni-icons
            type="clear"
            size="20"
            color="#F56C6C"
            class="img-icon"
            @tap="$refs.popup6.close()"
          ></uni-icons>
        </view>
      </scroll-view>
      <view
        style="width: 240px; text-align: center; padding: 10px; color: red"
        >{{ titelMsg }}</view
      >
      <view class="bottom-nav" style="bottom: -45px">
        <button
          type="primary"
          class="btn"
          @click="takeTestPiece(Number(indexNum))"
        >
          重新拍照
        </button>
      </view>

      <!-- <canvas
				id="canvas-clipperLose" 
				canvas-id="canvas-clipperLose" 
				type="2d" 
				:style="{
					width: canvasSiz.width+'px',
					height: canvasSiz.height+'px',
					position: 'fixed', 
					top: 0, 
					left: '-'+canvasSiz.width+'px'
				}" 
			/> -->
    </uni-popup>

    <!-- 检测样品封样方法指南 -->
    <uni-popup ref="popup5" type="bottom" background-color="#fff">
      <scroll-view
        scroll-y="true"
        style="width: 100vw; max-height: calc(100vh - 90px)"
        @click="$refs.popup5.close()"
      >
        <view style="width: 100vw">
          <image
            src="@/static/img/sample/help1.png"
            mode="widthFix"
            style="width: 100vw"
            v-if="meIndex == 1"
          ></image>
          <image
            src="@/static/img/sample/help2.png"
            mode="widthFix"
            style="width: 100vw"
            v-if="meIndex == 2"
          ></image>
          <image
            src="@/static/img/sample/help3.png"
            mode="widthFix"
            style="width: 100vw"
            v-if="meIndex == 3"
          ></image>
        </view>
      </scroll-view>
    </uni-popup>

    <!-- 初始化页面提示 -->
    <uni-popup
      class="tips-popup"
      ref="tipsPopup"
      :mask-click="false"
      background-color="#fff"
    >
      <view class="tips-title">温馨提示</view>
      <view class="tips-box">
        <text>1、见证人员应和取样人员同步进行取样检测过程拍摄； </text>
        <text>2、待取样人员提交检测信息后，见证人员方可进行检测信息核验；</text>
      </view>
      <view class="bottom-nav">
        <button type="primary" class="btn" @click="closeTips">确定</button>
      </view>
    </uni-popup>
    <view v-if="hintShow" class="hint">
      <view>
        <image
          style="width: 50px; height: 50px"
          src="../../static/img/succeeLog.png"
        ></image>
      </view>
      <view style="color: #fff">{{ hintTitle }}</view>
    </view>
  </view>
</template>

<script>
import urlConfig from "@/common/urlConfig.js";
import { parseTime } from "@/common/util.js";
import { base64File } from "@/api/index.js";

export default {
  data() {
    return {
      // 离线取样数据
      networkData: undefined,
      // 是否同步数据
      networkFlag: false,
      // 项目信息-判断是否有bim/全景
      projectInfo: {},
      // 检测样品封样方法指南
      meOptions: [
        { value: 0, name: "检测样品封样方法指南" },
        { value: 1, name: "中小型固体和液体试件封样方法" },
        { value: 2, name: "混凝土、砂浆试件封样方法" },
        { value: 3, name: "大中型试件封样方法" },
      ],
      meIndex: 0,
      // 人脸识别照片
      portraitImageSrc: "",
      // 二维码标识照片
      ewmImageSrc: "",
      // 试件照片
      imagesrc: [],
      imagesrcLater: [],
      // 示例视频播放
      videoPlay: false,
      videoUrl: "",
      // 试件音视频
      testVideoUrl: "",
      // 画布大小
      canvasSiz: {
        width: 320,
        height: 300,
      },
      // 是否生成随机框
      randomPostion: false,
      // 随机框数量
      specimenNums: null,
      specimenNumsRrr: [],
      // 表单提交
      form: {
        userPhotos: [], // 取样人员照片
        qrCodePhotos: [], // 二维码标识照片
        specimenPhotos: [], // 试件照片
        videoFiles: [], // 试件音视频
        bim: {}, // bim定位
        panoramic: {}, // 全景定位
      },
      photoFalg1: true, //判断拍照成功刷新地位框
      photoFalg2: true, //判断拍照成功刷新地位框
      photoFalg3: true, //判断拍照成功刷新地位框
      // 随机框
      photoFalgNums: {},
      path: "",
      boxBigTop: "",
      boxBigLeft: "",
      boxSmallTop: "",
      boxSmallLeft: "",
      loseGeneratedBoxList: [],
      indexNum: null,
      titelMsg: null,
      indexIMg: null,
      hintShow: false,
      hintTitle: null,
    };
  },
  onLoad(params) {
    this.projectInfo = uni.getStorageSync("projectInfo");
    this.randomPostion = params.randomPostion;
    this.specimenNums = JSON.parse(params.specimenNums);
    // this.specimenNums = 6
    this.specimenNumsRrr = [];
    if (this.specimenNums > 0) {
      for (var i = 0; i < this.specimenNums; i++) {
        this.specimenNumsRrr.push(i + 1);
        this.photoFalgNums[`photoFalg${i + 1}`] = true;
      }
    }
    console.log(
      this.specimenNums,
      params,
      "params",
      this.specimenNumsRrr,
      this.specimenNums
    );
  },
  onReady() {
    this.$nextTick(() => {
      this.$refs.tipsPopup.open("center");
    });
    if (this.randomPostion == "true") {
      if (this.specimenNums > 0) {
        this.imagesrc = [...this.specimenNumsRrr];
        this.imagesrcLater = [...this.specimenNumsRrr];
      } else {
        this.imagesrc = [1, 2, 3];
        this.imagesrcLater = [1, 2, 3];
      }
    } else {
      if (this.specimenNums > 0) {
        this.imagesrc = [...this.specimenNumsRrr];
        this.imagesrcLater = [...this.specimenNumsRrr];
      }
    }
    // 同步离线数据
    this.networkData = uni.getStorageSync("networkData");
  },
  methods: {
    // 同步离线数据
    async getNetworkData() {
      uni.showLoading({
        title: "同步本地数据中...",
        mask: true,
      });
      if (
        this.networkData.qrCodePhotos &&
        this.networkData.qrCodePhotos != ""
      ) {
        let qrCodeRes = await base64File(this.networkData.qrCodePhotos);
        if (qrCodeRes.code == 200) {
          this.ewmImageSrc = qrCodeRes.data.url;
          this.form.qrCodePhotos.push(qrCodeRes.data);
        }
      }
      if (this.networkData.videoFiles && this.networkData.videoFiles != "") {
        let videoRes = await base64File(this.networkData.videoFiles);
        if (videoRes.code == 200) {
          this.testVideoUrl = videoRes.data.url;
          this.form.videoFiles.push(videoRes.data);
        }
      }
      this.networkData.specimenPhotos.forEach(async (item) => {
        let photoRes = await base64File(item);
        if (photoRes.code == 200) {
          this.imagesrc.push(photoRes.data);
          this.imagesrcLater.push(photoRes.data);
          this.form.specimenPhotos.push(photoRes.data);
        }
      });
      this.networkFlag = true;
      uni.hideLoading();
    },
    //保存
    save() {
      if (this.form.userPhotos.length == 0) {
        uni.showToast({ title: "请上传取样人员照片", icon: "none" });
        return false;
      }
      if (this.form.qrCodePhotos.length == 0) {
        uni.showToast({ title: "请上传二维码标识照片", icon: "none" });
        return false;
      }
      if (this.randomPostion == "true") {
        if (this.specimenNums > 0) {
          for (var i = 0; i < this.imagesrc.length; i++) {
            if (this.imagesrc[i] == i + 1) {
              uni.showToast({ title: `请上传试件照片${i + 1}`, icon: "none" });
              return false;
            } else {
              this.form.specimenPhotos = this.imagesrc;
            }
          }
        } else {
          if (this.imagesrc[0] == 1) {
            uni.showToast({ title: "请上传试件照片1", icon: "none" });
            return false;
          } else if (this.imagesrc[1] == 2) {
            uni.showToast({ title: "请上传试件照片2", icon: "none" });
            return false;
          } else if (this.imagesrc[2] == 3) {
            uni.showToast({ title: "请上传试件照片3", icon: "none" });
            return false;
          } else {
            this.form.specimenPhotos = this.imagesrc;
          }
        }
      } else {
        if (this.imagesrc.length == 0) {
          uni.showToast({ title: "请上传试件照片", icon: "none" });
          return false;
        } else {
          this.form.specimenPhotos = this.imagesrc;
        }
      }
      console.log(this.form.specimenPhotos, "this.form.specimenPhotos");
      /* if (this.form.videoFiles.length == 0) {
				uni.showToast({ title: '请上传试件音视频', icon: 'none' })
				return false
			} */
      let sampleInfo = uni.getStorageSync("sampleInfo");
      this.form.longitude = sampleInfo.longitude;
      this.form.latitude = sampleInfo.latitude;
      this.form.typeId = sampleInfo.typeId;
      this.form.typeName = sampleInfo.typeName;
      this.form.projectId = sampleInfo.projectId;
      this.form.qrCode = sampleInfo.qrCode;
      console.log(this.form, "this.form");
      uni.setStorageSync("sampleInfo", this.form);
      uni.navigateTo({
        url: "/pages/sample/info?flag=" + this.networkFlag,
      });
    },
    // 关闭选中
    closeTips() {
      this.$refs.tipsPopup.close();
    },
    // 提示选中
    mePickerChange(e) {
      this.meIndex = e.detail.value;
      if (e.detail.value != 0) {
        this.$refs.popup5.open("center");
      }
    },
    // 人脸识别
    takeAuth() {
      uni.navigateTo({
        url: "/pages/camera/portrait/portrait",
      });
    },
    // 试件图片
    openPopup4(index) {
      this.indexIMg = index;
      this.$refs.popup4.open("center");
      console.log(index, "openPopup4");
    },
    // 拍摄试件照片
    takeTestPiece(index) {
      this.indexNum = index;
      console.log(index, "index", this.photoFalgNums);
      this.$refs.popup6.close();
      if (Object.keys(this.photoFalgNums).length > 0) {
        for (let key in this.photoFalgNums) {
          console.log(key.split("g")[1], index);
          if (this.imagesrc[index - 1] == index) {
            if (key.split("g")[1] == index) {
              uni.navigateTo({
                url:
                  "/pages/camera/camera?type=sample&randomPostion=" +
                  this.randomPostion +
                  "&" +
                  key +
                  "=" +
                  this.photoFalg1 +
                  "&indexNum=" +
                  index +
                  "&photoFalgNums=" +
                  JSON.stringify(this.photoFalgNums) +
                  "&specimenNums=" +
                  this.specimenNums,
              });
            }
          }
        }
      } else {
        if (typeof index == "number") {
          if (this.imagesrc[index - 1] == index) {
            console.log(
              this.photoFalg1,
              this.photoFalg2,
              this.photoFalg3,
              "this.photoFalg1"
            );
            if (index == 1) {
              uni.navigateTo({
                url:
                  "/pages/camera/camera?type=sample&randomPostion=" +
                  this.randomPostion +
                  "&photoFalg1=" +
                  this.photoFalg1 +
                  "&indexNum=" +
                  index,
              });
            } else if (index == 2) {
              uni.navigateTo({
                url:
                  "/pages/camera/camera?type=sample&randomPostion=" +
                  this.randomPostion +
                  "&photoFalg2=" +
                  this.photoFalg2 +
                  "&indexNum=" +
                  index,
              });
            } else if (index == 3) {
              uni.navigateTo({
                url:
                  "/pages/camera/camera?type=sample&randomPostion=" +
                  this.randomPostion +
                  "&photoFalg3=" +
                  this.photoFalg3 +
                  "&indexNum=" +
                  index,
              });
            }
          }
        }
        // else{
        // 	console.log(1232331,this.specimenNums,'会计师考试看看')
        // 	uni.navigateTo({
        // 		url: '/pages/camera/camera?type=sample&randomPostion='+this.randomPostion+'&photoFalg='+this.photoFalg
        // 	})
        // }
        if (this.randomPostion == "true") {
          if (this.imagesrc.length <= 3) {
            uni.navigateTo({
              url:
                "/pages/camera/camera?type=sample&randomPostion=" +
                this.randomPostion +
                "&photoFalg=" +
                this.photoFalg,
            });
          }
        } else {
          uni.navigateTo({
            url:
              "/pages/camera/camera?type=sample&randomPostion=" +
              this.randomPostion +
              "&photoFalg=" +
              this.photoFalg,
          });
        }
      }
    },
    // 拍照二维码照片
    takePicture() {
      uni.navigateTo({
        url: "/pages/camera/watermark/watermark",
      });
    },
    // 录视频
    takeVideo() {
      uni.chooseVideo({
        sourceType: ["camera"],
        success: (res) => {
          this.testVideoUrl = res.tempFilePath;
          this.savePhoto(res.tempFilePath, "videoFiles");
        },
        fail: (err) => {
          console.log("err: ", err);
        },
      });
    },
    // 播放试件音视频
    handlePlay(e) {
      let videoContext = uni.createVideoContext("video", this);
      videoContext.requestFullScreen({ direction: 90 });
    },
    // BIM定位
    bim() {
      uni.navigateTo({
        url: "/pages/bimPosition/index",
      });
    },
    // 全景定位
    overallView() {
      let token = uni.getStorageSync("token");
      let qrCode = uni.getStorageSync("sampleInfo").qrCode;
      uni.navigateTo({
        url: `/pages/testPhoto/testPhoto?token=${token}&projectId=${this.projectInfo.id}&qrCode=${qrCode}`,
      });
    },
    // 获取全景定位
    getOverallView(e) {
      this.form.panoramic = {
        x: e.x,
        y: e.y,
      };
    },
    //bim
    getBimView(e) {
      this.form.bim = {
        x: e[0],
        y: e[1],
        z: e[2],
      };
    },
    // 试件照片查看样例
    testPieceDemo(type) {
      let imgsArray = [];
      if (type == 1) {
        imgsArray[0] = this.portraitImageSrc;
      } else if (type == 2) {
        imgsArray[0] = this.ewmImageSrc;
      } else if (type == 3) {
        imgsArray[0] = require("@/static/img/test/test2.jpg");
      } else {
        imgsArray[0] = require("@/static/img/test/test3.jpg");
      }
      console.log(imgsArray, "imgsArray");
      uni.previewImage({
        current: 0,
        urls: imgsArray,
      });
    },
    // 移除试件照片
    delectImg(index) {
      let _this = this;
      let title = "删除照片后二维码和副码方框会重置，确认删除？";
      if (this.randomPostion != "true") {
        title = "确认删除？";
      }
      uni.showModal({
        title: title,
        success: function (res) {
          if (res.confirm) {
            if (_this.specimenNums > 0) {
              _this.imagesrc.splice(index, 1, index + 1);
              _this.imagesrcLater.splice(index, 1, index + 1);
              _this.$refs.popup4.close();
            } else {
              _this.imagesrc.splice(index, 1);
              _this.imagesrcLater.splice(index, 1);
              _this.$refs.popup4.close();
            }
          } else {
            _this.$refs.popup4.close();
          }
        },
      });

      console.log(this.imagesrc);
    },
    // 示例视频-查看样例
    videoShow() {
      this.videoPlay = true;
      this.videoUrl = require("@/static/video/test.mp4");
      setTimeout(() => {
        let videoContext = uni.createVideoContext("testvideo", this);
        videoContext.requestFullScreen({ direction: 90 });
      }, 200);
    },
    // 示例视频-全屏播放
    screenChange(e) {
      // 值true为进入全屏，false为退出全屏
      let fullScreen = e.detail.fullScreen;
      if (!fullScreen) {
        //退出全屏-隐藏播放盒子
        this.videoPlay = false;
      }
    },
    // 处理人脸识别照片
    setPortraitImage(e) {
      let _this = this;
      uni.getImageInfo({
        src: e.path,
        success: function (image) {
          _this.canvasSiz.width = image.width;
          _this.canvasSiz.height = image.height;
          uni.showLoading({
            mask: true,
            title: "人脸识别中...",
          });
          // 设置重置尺寸生效延迟
          setTimeout(() => {
            let ctx = uni.createCanvasContext("canvas-clipper", _this);
            ctx.drawImage(e.path, 0, 0, image.width, image.height);
            // 加水印文字
            ctx.setFillStyle("#17b914");
            ctx.setFontSize(32);
            ctx.fillText("取样人员照片", 20, 60);
            // 加个时间水印
            ctx.setFontSize(32);
            ctx.fillText(
              parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
              20,
              100
            );
            // 创建裁剪后图片
            // uni.showLoading({
            //   mask: true,
            //   title: ".tu1..",
            // });
            ctx.draw(false, () => {
              uni.canvasToTempFilePath(
                {
                  destWidth: image.width,
                  destHeight: image.height,
                  canvasId: "canvas-clipper",
                  fileType: "jpg",
                  success: function (res) {
                    // uni.showLoading({
                    //   mask: true,
                    //   title: ".tu2..",
                    // });
                    _this.portraitAuth(res.tempFilePath);
                  },
                },
                _this
              );
            });
          }, 200);
        },
      });
    },
    portraitAuth(path) {
		//  uni.showLoading({
        //               mask: true,
        //               title: ".tu3..",
        //             });
      uni.uploadFile({
        url: urlConfig + "/quality/faceBody/checkFaceBody",
        filePath: path,
        name: "file",
        header: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + uni.getStorageSync("token"),
        },
        success: (res) => {
          let data = JSON.parse(res.data);
          if (data.code == 200) {
            this.portraitImageSrc = path;
            this.savePhoto(path, "userPhotos");
          } else {
            uni.showToast({
              title: data.msg,
              icon: "none",
            });
          }
        },
        fail: (error) => {
          uni.hideLoading();
          uni.showToast({
            title: "识别失败",
            icon: "none",
          });
        },
      });
    },
    // 处理水印照片
    setWatermarkImage(e) {
      let _this = this;
      uni.getImageInfo({
        src: e.path,
        success: function (image) {
          _this.canvasSiz.width = image.width;
          _this.canvasSiz.height = image.height;
          uni.showLoading({
            mask: true,
            title: "照片上传中...",
          });
          // 设置重置尺寸生效延迟
          setTimeout(() => {
            let ctx = uni.createCanvasContext("canvas-clipper", _this);
            // 绘制图片
            ctx.drawImage(e.path, 0, 0, image.width, image.height);
            // 加水印文字
            ctx.setFillStyle("#17b914");
            ctx.setFontSize(32);
            ctx.fillText("二维码标识照片", 20, 50);
            // 加个时间水印
            ctx.setFontSize(32);
            ctx.fillText(
              parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
              20,
              100
            );
            // 创建裁剪后图片
            ctx.draw(false, () => {
              uni.canvasToTempFilePath(
                {
                  destWidth: image.width,
                  destHeight: image.height,
                  canvasId: "canvas-clipper",
                  fileType: "jpg",
                  success: function (res) {
                    _this.ewmImageSrc = res.tempFilePath;
                    _this.savePhoto(res.tempFilePath, "qrCodePhotos");
                  },
                },
                _this
              );
            });
          }, 200);
        },
      });
    },
    // 处理试件照片
    testPiece(e) {
      let { path, boxBigTop, boxBigLeft, boxSmallTop, boxSmallLeft, indexNum } =
        e;
      this.path = path;
      this.boxBigTop = boxBigTop;
      this.boxBigLeft = boxBigLeft;
      this.boxSmallTop = boxSmallTop;
      this.boxSmallLeft = boxSmallLeft;
      if (indexNum) {
        this.indexNum = indexNum;
      }
      let _this = this;
      uni.getImageInfo({
        src: path,
        success: function (image) {
          _this.canvasSiz.width = image.width;
          // _this.randomPostion == 'true'
          if (_this.specimenNums > 0) {
            _this.canvasSiz.height = image.width * 0.9375;
          } else {
            _this.canvasSiz.height = image.height;
          }
          uni.showLoading({
            mask: true,
            title: "照片上传中...",
          });
          // if(_this.randomPostion == 'true'){
          // 	_this.savePhoto1(path, 'specimenPhotos');
          // }else{
          // 设置重置尺寸生效延迟
          setTimeout(() => {
            let ctx = uni.createCanvasContext("canvas-clipper", _this);
            if (_this.specimenNums > 0) {
              ctx.drawImage(
                path,
                0,
                -(image.height - _this.canvasSiz.height) / 2,
                image.width,
                image.height
              );
            } else {
              ctx.drawImage(e.path, 0, 0, image.width, image.height);
            }
            //
            if (
              _this.randomPostion != "true" &&
              (_this.specimenNums <= 0 || _this.specimenNums == "null")
            ) {
              // 添加文字水印
              ctx.setFillStyle("#17b914");
              ctx.setFontSize(32);
              ctx.fillText("试件照片", 20, 50);
              // 加个时间水印
              ctx.setFontSize(32);
              ctx.fillText(
                parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
                20,
                100
              );
            }
            // 试件对应方框
            // if (_this.randomPostion == 'true') {
            // 	let scale = _this.canvasSiz.height/300;
            // 	ctx.setStrokeStyle('#e5e900');
            // 	ctx.strokeRect(boxBigLeft*scale,boxBigTop*scale,110*scale,110*scale);
            // 	ctx.setStrokeStyle('#ff000a');
            // 	ctx.strokeRect(boxSmallLeft*scale,boxSmallTop*scale,75*scale,75*scale);
            // }
            // 创建转化分辨率后图片
            ctx.draw(false, () => {
              uni.canvasToTempFilePath(
                {
                  destWidth: image.width,
                  destHeight: _this.canvasSiz.height,
                  canvasId: "canvas-clipper",
                  fileType: "jpg",
                  success: function (res) {
                    // 保存图片路径
                    if (
                      _this.randomPostion == "true" ||
                      _this.specimenNums > 0
                    ) {
                      _this.savePhoto1(res.tempFilePath, "specimenPhotos");
                    } else {
                      _this.savePhoto(res.tempFilePath, "specimenPhotos");
                    }
                  },
                },
                _this
              );
            });
          }, 200);
          // }
        },
      });
    },
    // 上传失败后 生成方框
    loseGeneratedBox() {
      let _this = this;
      uni.getImageInfo({
        src: _this.path,
        success: function (image) {
          console.log(image, "image");
          _this.canvasSiz.width = image.width;
          if (_this.randomPostion == "true") {
            _this.canvasSiz.height = image.width * 0.9375;
          } else {
            _this.canvasSiz.height = image.height;
          }
          // 设置重置尺寸生效延迟
          setTimeout(() => {
            let ctx = uni.createCanvasContext("canvas-clipper", _this);
            if (_this.randomPostion == "true") {
              ctx.drawImage(
                _this.path,
                0,
                -(image.height - _this.canvasSiz.height) / 2,
                image.width,
                image.height
              );
            } else {
              ctx.drawImage(_this.path, 0, 0, image.width, image.height);
            }
            // 试件对应方框
            if (_this.randomPostion == "true") {
              let scale = _this.canvasSiz.height / 300;
              ctx.setStrokeStyle("#e5e900");
              ctx.strokeRect(
                _this.boxBigLeft * scale,
                _this.boxBigTop * scale,
                110 * scale,
                110 * scale
              );
              ctx.setStrokeStyle("#ff000a");
              ctx.strokeRect(
                _this.boxSmallLeft * scale,
                _this.boxSmallTop * scale,
                75 * scale,
                75 * scale
              );
            }
            // 创建转化分辨率后图片
            ctx.draw(false, () => {
              uni.canvasToTempFilePath(
                {
                  destWidth: image.width,
                  destHeight: _this.canvasSiz.height,
                  canvasId: "canvas-clipper",
                  fileType: "jpg",
                  success: function (res) {
                    _this.loseGeneratedBoxList = [res.tempFilePath];
                    console.log(
                      _this.loseGeneratedBoxList,
                      "_this.loseGeneratedBoxList"
                    );
                    console.log(res.tempFilePath);
                    _this.$refs.popup6.open("center");
                    // uni.previewImage({
                    // 	current: 0,
                    // indicator:'number',
                    // 	urls: _this.loseGeneratedBoxList
                    // })
                    // canvas-clipperLose
                    // _this.$refs.popup6.open('center')
                    // if(_this.randomPostion == 'true'){
                    // 	_this.savePhoto1(res.tempFilePath, 'specimenPhotos');
                    // }else{
                    // 	_this.savePhoto(res.tempFilePath, 'specimenPhotos');
                    // }
                  },
                },
                _this
              );
            });
          }, 200);
        },
      });
    },
    //保存图片到相册，方便核查
    savePhoto(path, type) {
      uni.uploadFile({
        url: urlConfig + "/file/uploadFiles",
        filePath: path,
        name: "files",
        header: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + uni.getStorageSync("token"),
        },
        success: (res) => {
          uni.hideLoading();
          console.log(res, "err");
          let obj = JSON.parse(res.data);
          if (obj.code == 200) {
            console.log("文件上传成功");
            if (type == "userPhotos") {
              this.form.userPhotos = obj.data;
            } else if (type == "qrCodePhotos") {
              this.form.qrCodePhotos = obj.data;
            } else if (type == "specimenPhotos") {
              this.imagesrc.push(obj.data[0]);
              this.imagesrcLater.push(obj.data[0]);
            } else if (type == "videoFiles") {
              this.form.videoFiles = obj.data;
            }
          } else {
            uni.showToast({
              title: "文件上传失败",
              icon: "none",
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: "文件上传失败",
            icon: "none",
          });
        },
      });
      //保存到相册
      /* uni.saveImageToPhotosAlbum({
				filePath: path,
				success: () => {
					console.log(图片已存入相册)
				}
			}); */
    },
    // 存图片到相册，方便核查---主副码
    savePhoto1(path, type) {
      let sampleInfo = uni.getStorageSync("sampleInfo");
      let scale = this.canvasSiz.height / 300;
      let obj = {
        order: this.indexNum,
        qrcode: sampleInfo.qrCode,
        qrcodeArea: {
          x: parseInt(this.boxBigLeft * scale),
          y: parseInt(this.boxBigTop * scale),
          width: parseInt(110 * scale),
          height: parseInt(110 * scale),
        },
        referenceArea: {
          x: parseInt(this.boxSmallLeft * scale),
          y: parseInt(this.boxSmallTop * scale),
          width: parseInt(75 * scale),
          height: parseInt(75 * scale),
        },
        randomPostion: this.randomPostion,
      };
      if (this.randomPostion != "true") {
        obj.qrcodeArea = {};
        obj.referenceArea = {};
      }
      console.log(this.indexNum, "this.indexNum", obj);
      uni.uploadFile({
        url: urlConfig + "/file/uploadSamplingFiles",
        filePath: path,
        name: "file",
        header: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + uni.getStorageSync("token"),
        },
        formData: {
          pieceInfo: JSON.stringify(obj),
        },
        success: (res) => {
          uni.hideLoading();
          console.log(res, "err");
          let obj = JSON.parse(res.data);
          if (obj.code == 200) {
            if (Object.keys(this.photoFalgNums).length > 0) {
              for (let key in this.photoFalgNums) {
                if (this.indexNum == key.split("g")[1]) {
                  this.photoFalgNums[key] = true;
                }
              }
            } else {
              if (this.indexNum == 1) {
                this.photoFalg1 = true;
              } else if (this.indexNum == 2) {
                this.photoFalg2 = true;
              } else if (this.indexNum == 3) {
                this.photoFalg3 = true;
              }
            }
            console.log("文件上传成功");
            if (type == "userPhotos") {
              this.form.userPhotos = obj.data;
            } else if (type == "qrCodePhotos") {
              this.form.qrCodePhotos = obj.data;
            } else if (type == "specimenPhotos") {
              this.hintTitle = obj.msg;
              setTimeout(() => {
                this.hintShow = true;
                setTimeout(() => {
                  this.hintShow = false;
                }, 2000);
              }, 500);
              this.imagesrc.splice(this.indexNum - 1, 1, obj.data);
              this.testPieceLater();
              // this.imagesrc[this.indexNum-1] = obj.data
              console.log(this.imagesrc, "this.imagesrc");
              // this.imagesrc.push(obj.data)
            } else if (type == "videoFiles") {
              this.form.videoFiles = obj.data;
            }
          } else {
            let obj = JSON.parse(res.data);
            if (type == "specimenPhotos" && this.randomPostion == "true") {
              this.titelMsg = obj.msg;
              // uni.showToast({
              // 	title: obj.msg,
              // 	icon: 'none'
              // })
              this.loseGeneratedBox();
            } else {
              uni.showToast({
                title: obj.msg,
                icon: "none",
              });
            }
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            title: "文件上传失败",
            icon: "none",
          });
        },
      });
      //保存到相册
      /* uni.saveImageToPhotosAlbum({
				filePath: path,
				success: () => {
					console.log(图片已存入相册)
				}
			}); */
    },
    // 上传成功后处理照片
    testPieceLater(e) {
      let _this = this;
      uni.getImageInfo({
        src: _this.path,
        success: function (image) {
          console.log(image, "image");
          _this.canvasSiz.width = image.width;
          if (_this.specimenNums > 0) {
            _this.canvasSiz.height = image.width * 0.9375;
          } else {
            _this.canvasSiz.height = image.height;
          }
          // 设置重置尺寸生效延迟
          setTimeout(() => {
            let ctx = uni.createCanvasContext("canvas-clipper", _this);
            if (_this.specimenNums > 0) {
              ctx.drawImage(
                _this.path,
                0,
                -(image.height - _this.canvasSiz.height) / 2,
                image.width,
                image.height
              );
            } else {
              ctx.drawImage(_this.path, 0, 0, image.width, image.height);
            }
            ctx.setFillStyle("#17b914");
            ctx.setFontSize(32);
            ctx.fillText("试件照片", 20, 50);
            // 加个时间水印
            ctx.setFontSize(32);
            ctx.fillText(
              parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
              20,
              100
            );
            // 试件对应方框
            if (_this.randomPostion == "true") {
              let scale = _this.canvasSiz.height / 300;
              ctx.setStrokeStyle("#e5e900");
              ctx.strokeRect(
                _this.boxBigLeft * scale,
                _this.boxBigTop * scale,
                110 * scale,
                110 * scale
              );
              ctx.setStrokeStyle("#ff000a");
              ctx.strokeRect(
                _this.boxSmallLeft * scale,
                _this.boxSmallTop * scale,
                75 * scale,
                75 * scale
              );
            }
            // 创建转化分辨率后图片
            ctx.draw(false, () => {
              uni.canvasToTempFilePath(
                {
                  destWidth: image.width,
                  destHeight: _this.canvasSiz.height,
                  canvasId: "canvas-clipper",
                  fileType: "jpg",
                  success: function (res) {
                    _this.imagesrcLater.splice(_this.indexNum - 1, 1, {
                      url: res.tempFilePath,
                    });
                    // uni.previewImage({
                    // 	current: 0,
                    // indicator:'number',
                    // 	urls: _this.loseGeneratedBoxList
                    // })
                    // canvas-clipperLose
                    // _this.$refs.popup6.open('center')
                    // if(_this.randomPostion == 'true'){
                    // 	_this.savePhoto1(res.tempFilePath, 'specimenPhotos');
                    // }else{
                    // 	_this.savePhoto(res.tempFilePath, 'specimenPhotos');
                    // }
                  },
                },
                _this
              );
            });
          }, 200);
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
#sample {
  padding: 10px 0 60px 0;
  background-color: #fafafa;
  min-height: calc(100vh - 44px);

  .uni-list {
    .test-piece {
      width: 64px;
      height: 64px;
      display: flex;
      overflow: hidden;
      justify-content: center;
    }
    .help {
      height: 42px;
      display: flex;
      padding: 0 10px;
      position: relative;
      align-items: center;
      border-top: 1rpx solid #eee;
      border-bottom: 1rpx solid #eee;

      .help-text {
        white-space: nowrap;
      }
      uni-picker {
        flex: 1;

        .uni-input {
          font-size: 12px;
          text-align: right;
          padding-right: 30px;
        }
        .arrowright {
          padding-right: 10px;
        }
      }
      .arrowright {
        right: 0;
        top: 12px;
        position: absolute;
      }
    }
    .sub-title {
      padding: 0 10px;
      line-height: 42px;
      position: relative;
      border-bottom: 1rpx solid #eee;
      uni-text {
        white-space: nowrap;
      }
      .title-btn {
        top: 6px;
        right: 6px;
        width: 100px;
        font-size: 12px;
        position: absolute;
      }
    }
    .slot-box {
      .slot-image {
        width: 46px;
        height: 46px;
        border-radius: 4px;
        border: 3px solid #407ffe;
      }
    }
    .slot-body {
      flex: 1;
      padding: 6px 0;
      font-size: 16px;
      margin-left: 20px;

      .slot-text {
        color: #e1e2e4;
        margin-top: 6px;
      }
      .slot-font {
        color: #b3b3b3;
        font-size: 12px;
        margin-top: 6px;
      }
      .slot-link {
        color: #007aff;
        font-size: 12px;
        margin-top: 6px;
      }
    }
  }
  .bottom-nav {
    left: 0;
    bottom: 0;
    width: 100vw;
    height: 50px;
    padding: 10px;
    position: fixed;
    background-color: #fff;
    box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, 0.1);
  }

  .tips-popup {
    /deep/.uni-popup__wrapper {
      border-radius: 5px;
    }
    .tips-title {
      font-size: 18px;
      text-align: center;
      line-height: 36px;
      border-bottom: 1rpx solid #eee;
    }
    .tips-box {
      width: 70vw;
      padding: 10px 13px;
      padding-bottom: 60px;
      uni-text {
        display: block;
        font-size: 14px;
      }
    }
    .bottom-nav {
      left: 0;
      bottom: 0;
      width: 100%;
      height: 50px;
      padding: 10px;
      position: absolute;
      background-color: #fff;
      box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, 0.1);
    }
  }

  .preview-img {
    margin: 10px;
    width: 240px;
    display: flex;
    position: relative;
    align-items: center;

    .img-icon {
      top: 10px;
      right: 10px;
      font-size: 20px;
      position: absolute;
    }
  }
  .hint {
    background: #414144;
    position: fixed;
    width: 380rpx;
    top: 50%;
    left: 50%;
    margin-left: -190rpx;
    margin-top: -25px;
    text-align: center;
    border-radius: 10rpx;
    padding: 30rpx;
    display: flex;
    flex-direction: column;
  }
}
</style>
